
use anyhow::Result;
use hyper::{Client, client::HttpConnector};

use serde::{Deserialize, Serialize};
use serde_json::Value;

use crate::rpc::{JsonRpcRequest, jsonrpc_request};

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct SectorStatus {
    #[serde(rename(deserialize = "SectorID"))]
    pub sector_id: u64,
    pub state: String,
}

pub async fn query_sector_status(client: &Client<HttpConnector>, url: &str, token: &str, sector: u64) -> Result<SectorStatus>{
    let params = vec![Value::from(sector), Value::from(false)];
    let req = JsonRpcRequest::with_params("Filecoin.SectorsStatus", params);
    let r = jsonrpc_request::<SectorStatus>(client, url, token, req).await?;
    match r {
        None => Err(anyhow::anyhow!("sector {} status not found.", sector)),
        Some(v) => Ok(v),
    }
}

pub async fn query_sector_list(client: &Client<HttpConnector>, url: &str, token: &str, states: Option<Vec<&str>>) -> Result<Vec<u64>> {
    let req = if states.is_none() {
        JsonRpcRequest::with_params("Filecoin.SectorsListInStates", vec![])
    } else {
        let param = states.unwrap();
        if param.is_empty(){
            JsonRpcRequest::with_params("Filecoin.SectorsListInStates", vec![])
        } else {
            JsonRpcRequest::with_params("Filecoin.SectorsListInStates", vec![Value::from(param)])
        }
    };

    let r = jsonrpc_request::<Vec<u64>>(client, url, token, req).await?;
    match r {
        None => Ok(Vec::<u64>::with_capacity(0)),
        Some(v) => Ok(v),
    }
}